package com.yulan.fastkillcourse.mq;


import com.yulan.fastkillcourse.model.CourseMargin;
import com.yulan.fastkillcourse.model.CourseOrder;
import com.yulan.fastkillcourse.redis.RedisService;
import com.yulan.fastkillcourse.redis.key.CourseKey;
import com.yulan.fastkillcourse.service.CourseMarginService;
import com.yulan.fastkillcourse.service.CourseOrderService;
import com.yulan.fastkillcourse.service.CourseService;
import com.yulan.fastkillcourse.service.FastkillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class MQReceiver {

    private static Logger log = LoggerFactory.getLogger(MQReceiver.class);


    @Autowired
    RedisService redisService;

    @Autowired
    CourseOrderService courseOrderService;

    @Autowired
    CourseService courseService;

    @Autowired
    CourseMarginService courseMarginService;

    @Autowired
    FastkillService fastkillService;

    private static ReentrantLock lock = new ReentrantLock();

    private  static AtomicInteger count = new AtomicInteger(1);

    @Transactional
    @RabbitListener(queues= MQConfig.FASTKILL_QUEUE1,concurrency = "1")
    public void receive1(String message){
        log.info("receive1 message:"+message);
        FastKillMessage mm = RedisService.stringToBean(message,FastKillMessage.class);
        int uid = mm.getUid();
        int cid = mm.getCid();
        //获取课程余量
        CourseMargin courseMargin = courseMarginService.getById(cid);
        if(courseMargin==null){
            return ;
        }
        int stock = courseMargin.getMargin();
        if(stock<=0) return;


        boolean updateSuccess = fastkillService.DoFastKill(uid,cid);
        if (updateSuccess) count.incrementAndGet();
        System.out.println("1+"+count);
    }


}
